package com.hmob.hmdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hmob.hmsdk.ads.AdError;
import com.hmob.hmsdk.ads.nativ.HMNative;
import com.hmob.hmsdk.ads.nativ.NativeListener;
import com.hmob.hmsdk.entity.NativeResource;

import java.util.List;

public class NativeActivity extends AppCompatActivity {

    private List<NativeResource> mList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_native);
        final View adContainer = findViewById(R.id.ad_container);
        final TextView tvTitle = findViewById(R.id.title);
        final TextView tvContent = findViewById(R.id.content);
        final ImageView ivImage = findViewById(R.id.image);
        View loadAd = findViewById(R.id.load_ad);
        loadAd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //1、创建广告对象
                HMNative hmNative = new HMNative(NativeActivity.this, Constants.ADID_NATIVE, new NativeListener() {
                    @Override
                    public void onADReceived(List<NativeResource> list) {
                        mList = list;
                        Toast.makeText(NativeActivity.this, "广告获取成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNoAD(AdError adError) {
                        Log.e("NativeActivity", adError.getErrorMessage());
                    }
                });
                //2、加载广告，可预加载多条，范围1-5，可能有重复广告
                hmNative.load(1);
            }
        });

        View showAd = findViewById(R.id.show_ad);
        showAd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mList == null || mList.size() == 0)
                    return;
                //获取广告信息并展示
                final NativeResource nativeResource = mList.get(0);
                tvTitle.setText(nativeResource.getTitle());
                tvContent.setText(nativeResource.getDescription());
                Glide.with(NativeActivity.this).load(nativeResource.getImage().get(0)).into(ivImage);
                //展示成功后调用SDK方法反馈
                nativeResource.onExposed(adContainer);
                //一定要先调用onExposed方法曝光广告，否则将无法调用onTouch方法
                adContainer.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        nativeResource.onTouch(v, event);
                        return true;
                    }
                });
            }
        });

    }

}
